package com.eostoken.eos_wallet.ui.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eostoken.eos_wallet.MyApplication;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseFragment;
import com.eostoken.eos_wallet.bean.AccountInfo;
import com.eostoken.eos_wallet.bean.MsgCodeBean;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.eosnet.common.EOSNetWorkManager;
import com.eostoken.eos_wallet.mvp.mode.HomeModel;
import com.eostoken.eos_wallet.mvp.presenter.HomePresenterImpl;
import com.eostoken.eos_wallet.mvp.view.HomeView;
import com.eostoken.eos_wallet.net.common.NetWorkManager;
import com.eostoken.eos_wallet.test.TestActivity;
import com.eostoken.eos_wallet.ui.activity.BindWalletActivity;
import com.eostoken.eos_wallet.ui.activity.LanguageActivity;
import com.eostoken.eos_wallet.ui.activity.MidQRCodeActivity;
import com.eostoken.eos_wallet.ui.activity.MoneyReceivingQRCodeActivity;
import com.eostoken.eos_wallet.ui.activity.MyWalletInfoActivity;
import com.eostoken.eos_wallet.ui.activity.StimulateActivity;
import com.eostoken.eos_wallet.ui.activity.WalletFunctionActivity;
import com.eostoken.eos_wallet.ui.activity.WebActivity;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.RSAUtils;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;

import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static com.eostoken.eos_wallet.utils.Constants.ACCOUNT_INFO;
import static com.eostoken.eos_wallet.utils.Constants.AYING_URL;
import static com.eostoken.eos_wallet.utils.Constants.AYING_URL_EOS;
import static com.eostoken.eos_wallet.utils.Constants.CORPORATION_URL;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_TO_URL;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_TRANSACTION_LIST;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.GET_BIND_ADDRESS;
import static com.eostoken.eos_wallet.utils.Constants.GUOYU_URL;
import static com.eostoken.eos_wallet.utils.Constants.LANGUAGE_SETUP;
import static com.eostoken.eos_wallet.utils.Constants.OFFICIAL_URL_EOS;
import static com.eostoken.eos_wallet.utils.Constants.PROCEEDS;
import static com.eostoken.eos_wallet.utils.Constants.TESTURL;
import static com.eostoken.eos_wallet.utils.Constants.TESTURL_EOS;
import static com.eostoken.eos_wallet.utils.Constants.WALLET_INFO;
import static com.eostoken.eos_wallet.utils.Constants.WALLET_MANAGEMENT;

public class MyFragment extends BaseFragment<HomeModel, HomeView, HomePresenterImpl> implements HomeView {

    @BindView(R.id.groupListView)
    QMUIGroupListView groupListView;
    @BindView(R.id.topbar)
    QMUITopBarLayout topbar;
    @BindView(R.id.appVersionTv)
    AppCompatTextView appVersionTv;

    private String currentAccountName;
    private String privatekey;
    private MgpWallet wallet;
    private AccountInfo accountInfo;
    private QMUICommonListItemView walletItem;
    private String walletName;
    private QMUICommonListItemView myInvitationCodeItem, bindEthAddressItem;
    private QMUIBottomSheet qmuiBottomSheet;
    private List<String> serverList;
    private List<String> eosServerList;
    private int i = 0;
    private int bindCode = -1;

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_dashboard;
    }

    @Override
    protected void initData() {
        if (wallet != null) {
            wallet = WalletUtils.getCurrentWallet(getActivity());
            currentAccountName = wallet.getCurrentAccountName();
            privatekey = wallet.getPrivateKey();
        }
        serverList = CollectionUtils.newArrayList();
        serverList.add(getString(R.string.str_online_server));
        serverList.add(getString(R.string.str_test_server));
        serverList.add(getString(R.string.str_guoyu_server));
//        serverList.add(getString(R.string.str_aying_server));
        eosServerList = CollectionUtils.newArrayList();
        eosServerList.add(getString(R.string.str_online_eos_server));
        eosServerList.add(getString(R.string.str_test_eos_server));
        eosServerList.add(getString(R.string.str_aying_eos_server));
    }

    @Override
    protected void initView(View contentView) {
        topbar.setTitle(StringUtils.getString(R.string.str_my));
        appVersionTv.setVisibility(View.VISIBLE);
        appVersionTv.setText("V" + AppUtils.getAppVersionName());
        initGroupListView();
        showSwitchServer();
    }

    private void initGroupListView() {

        if (ObjectUtils.isEmpty(wallet)) {
            walletName = getString(R.string.str_mgp_wallet_1);
        } else {
            walletName = ObjectUtils.isEmpty(wallet.getWalletName()) ? getString(R.string.str_mgp_wallet_1) : wallet.getWalletName();
        }
        walletItem = groupListView.createItemView(
                ContextCompat.getDrawable(getContext(), R.mipmap.eostoken_logo),
                walletName,
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        walletItem.setOrientation(QMUICommonListItemView.VERTICAL);

        ///////////////////////////////////////////////

        myInvitationCodeItem = groupListView.createItemView(
                ContextCompat.getDrawable(getContext(), R.mipmap.invitation_code_icon),
                getString(R.string.str_my_invitation_code),
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        myInvitationCodeItem.setOrientation(QMUICommonListItemView.VERTICAL);
        myInvitationCodeItem.setVisibility(ObjectUtils.isEmpty(MyApplication.getInstance().mMid) ? View.GONE : View.VISIBLE);
        QMUICommonListItemView myMgpStimulateItem = groupListView.createItemView(
                ContextCompat.getDrawable(getContext(), R.mipmap.stimulate_icon),
                getString(R.string.str_my_mgp_stimulate),
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        myMgpStimulateItem.setOrientation(QMUICommonListItemView.VERTICAL);

        bindEthAddressItem = groupListView.createItemView(
                ContextCompat.getDrawable(getContext(), R.mipmap.bind_wallet_icon),
                getString(R.string.str_bind_eth_address),
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        bindEthAddressItem.setOrientation(QMUICommonListItemView.HORIZONTAL);

        ////////////////////////////////////////////////////////////
        QMUICommonListItemView receiptQRCodeItem = groupListView.createItemView(
                ContextCompat.getDrawable(getContext(), R.mipmap.shroff_account_icon),
                getString(R.string.str_my_receiving_QRcode),
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        receiptQRCodeItem.setOrientation(QMUICommonListItemView.VERTICAL);

        QMUICommonListItemView transactionRecordItem = groupListView.createItemView(
                ContextCompat.getDrawable(getContext(), R.mipmap.transaction_record_icon),
                getString(R.string.str_transaction_record),
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        transactionRecordItem.setOrientation(QMUICommonListItemView.VERTICAL);

        QMUICommonListItemView languageSettingsItem = groupListView.createItemView(
                ContextCompat.getDrawable(getContext(), R.mipmap.language_settings_icon),
                getString(R.string.str_language_settings),
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        languageSettingsItem.setOrientation(QMUICommonListItemView.VERTICAL);

        QMUICommonListItemView aboutUsItem = groupListView.createItemView(
                ContextCompat.getDrawable(getContext(), R.mipmap.aboutus_icon),
                getString(R.string.str_about_us),
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        aboutUsItem.setOrientation(QMUICommonListItemView.VERTICAL);

        QMUICommonListItemView testItem = groupListView.createItemView(
                ContextCompat.getDrawable(getContext(), R.mipmap.aboutus_icon),
                "test",
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        testItem.setOrientation(QMUICommonListItemView.VERTICAL);

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment fragment = null;
                Bundle bundle;
                Intent intent;
                String destTag = "";
                int type = -1;
                if (v instanceof QMUICommonListItemView) {
                    CharSequence text = ((QMUICommonListItemView) v).getText();
                    if (ObjectUtils.equals(text, walletName)) {
                        type = WALLET_MANAGEMENT;
                        intent = new Intent(getActivity(), MyWalletInfoActivity.class);
                        bundle = new Bundle();
                        bundle.putParcelable(EXTRA_WALLET, wallet);
                        intent.putExtras(bundle);
                        ActivityUtils.startActivity(intent);
//                        return;
                    } else if (ObjectUtils.equals(StringUtils.getString(R.string.str_my_receiving_QRcode), text)) {
                        type = PROCEEDS;
                        intent = new Intent(getActivity(), MoneyReceivingQRCodeActivity.class);
                        ActivityUtils.startActivity(intent);
                    } else if (ObjectUtils.equals(StringUtils.getString(R.string.str_transaction_record), text)) {
                        type = WALLET_INFO;
                        intent = new Intent(getActivity(), WalletFunctionActivity.class);
                        bundle = new Bundle();
                        bundle.putBoolean(EXTRA_TRANSACTION_LIST, true);
                        intent.putExtras(bundle);
                        ActivityUtils.startActivity(intent);
                    } else if (ObjectUtils.equals(StringUtils.getString(R.string.str_language_settings), text)) {
                        type = LANGUAGE_SETUP;
                        intent = new Intent(getActivity(), LanguageActivity.class);
                        ActivityUtils.startActivity(intent);
                    } else if (ObjectUtils.equals(StringUtils.getString(R.string.str_about_us), text)) {
//                        String aboutus_url = "https://mangochain.io";
//                        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(aboutus_url));
//                        startActivity(browserIntent);
                        String aboutus_url = "https://mangochain.io";
                        Intent browserIntent = new Intent(getActivity(), WebActivity.class);
                        browserIntent.putExtra(EXTRA_TO_URL, aboutus_url);
                        startActivity(browserIntent);
                    } else if (ObjectUtils.equals(getString(R.string.str_my_invitation_code), text)) {
                        if (ObjectUtils.isEmpty(MyApplication.getInstance().mMid)) {
                            ToastUtils.showShort(StringUtils.getString(R.string.str_please_active_mid));
                        } else {
                            intent = new Intent(getActivity(), MidQRCodeActivity.class);
                            intent.putExtra("mid", MyApplication.getInstance().mMid);
                            ActivityUtils.startActivity(intent);
                        }
                    } else if (ObjectUtils.equals(getString(R.string.str_my_mgp_stimulate), text)) {
                        if (ObjectUtils.isEmpty(MyApplication.getInstance().mMid)) {
                            ToastUtils.showShort(StringUtils.getString(R.string.str_please_active_mid));
                        } else {
                            intent = new Intent(getActivity(), StimulateActivity.class);
                            intent.putExtra("isShowState", true);
                            ActivityUtils.startActivity(intent);
                        }
                    } else if (ObjectUtils.equals(getString(R.string.str_bind_eth_address), text)) {
                        //备注: 0绑定成功 1绑定中 2 需绑定 3 错误信息(直接弹出)  5暂未开启
                        if (bindCode == 0 || bindCode == 2)
                            ActivityUtils.startActivity(BindWalletActivity.class);
                    } else if (ObjectUtils.equals("test", text)) {
                        ActivityUtils.startActivity(TestActivity.class);
                    }

                }
            }
        };

        int size = QMUIDisplayHelper.dp2px(getContext(), 30);
        QMUIGroupListView.newSection(getContext())
                .setTitle("")
                .setDescription("")
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(walletItem, onClickListener)
                .setMiddleSeparatorInset(QMUIDisplayHelper.dp2px(getContext(), 5), 0)
                .addTo(groupListView);

        QMUIGroupListView.newSection(getContext())
                .setLeftIconSize(QMUIDisplayHelper.dp2px(getContext(), 20), ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(myInvitationCodeItem, onClickListener)
                .addItemView(myMgpStimulateItem, onClickListener)
                .addItemView(bindEthAddressItem, onClickListener)
                .addTo(groupListView);

        QMUIGroupListView.newSection(getContext())
                .setLeftIconSize(QMUIDisplayHelper.dp2px(getContext(), 20), ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(receiptQRCodeItem, onClickListener)
                .addItemView(transactionRecordItem, onClickListener)
                .addItemView(languageSettingsItem, onClickListener)
                .addItemView(aboutUsItem, onClickListener)
                .addTo(groupListView);
    }

    @Override
    public void updateView(Object data, int responseSuccessCode) {
        switch (responseSuccessCode) {
            case ACCOUNT_INFO:
                accountInfo = (AccountInfo) data;
//                accountInfoJson = GsonUtils.toJson(accountInfo);
                break;
            case GET_BIND_ADDRESS:
                if (!ObjectUtils.isEmpty(data)) {
                    MsgCodeBean msgCodeBean = GsonUtils.fromJson(data.toString(), MsgCodeBean.class);
                    if (msgCodeBean != null) {
                        bindCode = msgCodeBean.getCode();
                        String msg = msgCodeBean.getMsg();
                        bindEthAddressItem.setVisibility(View.VISIBLE);
                        if (bindCode == 3) {
                            ToastUtils.showLong(msgCodeBean.getMsg());
                        } else if (bindCode == 5) {
                            bindEthAddressItem.setVisibility(View.GONE);
                        }
                        if (msg.contains("0x")) {
                            String s1 = msg.substring(0, 5);
                            String s2 = msg.substring(msg.length() - 5, msg.length());
                            msg = s1 + "..." + s2;
                        }
                        bindEthAddressItem.setDetailText(msg);
                    }
                }
                break;
        }
    }

    @Override
    public void onFailure(Object data, int responseFailCode) {
        switch (responseFailCode) {
            case ACCOUNT_INFO:
//                ToastUtils.showShort((String) data);
                break;
            case GET_BIND_ADDRESS:
                bindEthAddressItem.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public HomeModel createModel() {
        return new HomeModel();
    }

    @Override
    public HomeView createView() {
        return this;
    }

    @Override
    public HomePresenterImpl createPresenter() {
        return new HomePresenterImpl(getActivity());
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (wallet != null) {
            wallet = WalletUtils.getCurrentWallet(getActivity());
            currentAccountName = wallet.getCurrentAccountName();
            privatekey = wallet.getPrivateKey();
        }
        if (!hidden) {
            updateWalletNameView();
            getBindWalletAddress();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (wallet != null) {
            wallet = WalletUtils.getCurrentWallet(getActivity());
            currentAccountName = wallet.getCurrentAccountName();
            privatekey = wallet.getPrivateKey();
        }
        updateWalletNameView();
        getBindWalletAddress();
    }

    private void updateWalletNameView() {
        if (ObjectUtils.isEmpty(wallet)) {
            walletName = getString(R.string.str_mgp_wallet_1);
        } else {
            walletName = ObjectUtils.isEmpty(wallet.getWalletName()) ? getString(R.string.str_mgp_wallet_1) : wallet.getWalletName();
        }
        walletItem.setText(walletName);

        myInvitationCodeItem.setVisibility(ObjectUtils.isEmpty(MyApplication.getInstance().mMid) ? View.GONE : View.VISIBLE);
    }

    private void getBindWalletAddress() {
        if (ObjectUtils.isEmpty(currentAccountName)) {
            wallet = WalletUtils.getCurrentWallet(getActivity());
            currentAccountName = wallet.getCurrentAccountName();
            privatekey = wallet.getPrivateKey();
        }
        try {
            Map params = MapUtils.newHashMap();
            params.put("currentAddr", currentAccountName);
            params.put("type", "2");
            String jsonData2 = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData2);
            presenter.requestGetBindWalletAddress(content, GET_BIND_ADDRESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showSwitchServer() {
        appVersionTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                i++;
                if (i == 5) {
                    showSimpleBottomSheetList(false);
                    i = 0;
                }
            }
        });

        topbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                i++;
                if (i == 5) {
                    showSimpleBottomSheetList(true);
                    i = 0;
                }
            }
        });
    }

    private void showSimpleBottomSheetList(boolean isEOSURL) {
        QMUIBottomSheet.BottomListSheetBuilder builder = new QMUIBottomSheet.BottomListSheetBuilder(getActivity())
                .setGravityCenter(false)
                .setSkinManager(QMUISkinManager.defaultInstance(getActivity()))
                .setTitle(getString(R.string.str_select_server))
                .setAddCancelBtn(true)
                .setAllowDrag(true)
                .setNeedRightMark(true)
                .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                        dialog.dismiss();
                        String accountName = "";
                        String serverName = "";
                        if (isEOSURL) {
                            accountName = eosServerList.get(position);
                            serverName = OFFICIAL_URL_EOS;
                            if (ObjectUtils.equals(getString(R.string.str_online_eos_server), accountName)) {
                                serverName = OFFICIAL_URL_EOS;
                            } else if (ObjectUtils.equals(getString(R.string.str_test_eos_server), accountName)) {
                                serverName = TESTURL_EOS;
                            } else if (ObjectUtils.equals(getString(R.string.str_aying_eos_server), accountName)) {
                                serverName = AYING_URL_EOS;
                            }
                            SPUtils.getInstance(Constants.SP_MangoWallet_info).put(Constants.KEY_EOS_SERVER, serverName);
                        } else {
                            accountName = serverList.get(position);
                            serverName = CORPORATION_URL;
                            if (ObjectUtils.equals(getString(R.string.str_online_server), accountName)) {
                                serverName = CORPORATION_URL;
                            } else if (ObjectUtils.equals(getString(R.string.str_test_server), accountName)) {
                                serverName = TESTURL;
                            } else if (ObjectUtils.equals(getString(R.string.str_guoyu_server), accountName)) {
                                serverName = GUOYU_URL;
                            } else if (ObjectUtils.equals(getString(R.string.str_aying_server), accountName)) {
                                serverName = AYING_URL;
                            }
                            SPUtils.getInstance(Constants.SP_MangoWallet_info).put(Constants.KEY_SERVER, serverName);
                        }
                        NetWorkManager.reSetRequest();
                        EOSNetWorkManager.reSetRequest();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                AppUtils.relaunchApp();
                            }
                        }, 3000);
                    }
                });
        String serverName = "";
        if (isEOSURL) {
            for (int i = 0; i < eosServerList.size(); i++) {
                String itemstr = eosServerList.get(i);
                builder.addItem(itemstr);
            }
            serverName = SPUtils.getInstance(Constants.SP_MangoWallet_info).getString(Constants.KEY_EOS_SERVER, OFFICIAL_URL_EOS);
            if (ObjectUtils.equals(serverName, OFFICIAL_URL_EOS))
                builder.setCheckedIndex(0);
            else if (ObjectUtils.equals(serverName, TESTURL_EOS))
                builder.setCheckedIndex(1);
            else if (ObjectUtils.equals(serverName, AYING_URL_EOS))
                builder.setCheckedIndex(2);
            else
                builder.setCheckedIndex(0);
        } else {
            for (int i = 0; i < serverList.size(); i++) {
                String itemstr = serverList.get(i);
                builder.addItem(itemstr);
            }
            serverName = SPUtils.getInstance(Constants.SP_MangoWallet_info).getString(Constants.KEY_SERVER, CORPORATION_URL);
            if (ObjectUtils.equals(serverName, CORPORATION_URL))
                builder.setCheckedIndex(0);
            else if (ObjectUtils.equals(serverName, TESTURL))
                builder.setCheckedIndex(1);
            else if (ObjectUtils.equals(serverName, GUOYU_URL))
                builder.setCheckedIndex(2);
            else if (ObjectUtils.equals(serverName, AYING_URL))
                builder.setCheckedIndex(3);
            else
                builder.setCheckedIndex(0);
        }

        qmuiBottomSheet = builder.build();
        if (qmuiBottomSheet != null)
            if (!qmuiBottomSheet.isShowing())
                qmuiBottomSheet.show();
    }
}
